<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" v-show="showDept" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :class="{'table-layout':!showDept}" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button size="mini" @click="onShowDept">
              {{showDept ? '隐藏部门':'显示部门'}}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:user:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
            >导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
            >导出
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="用户编号" align="center" prop="userId"/>
          <el-table-column label="用户名称" align="center" prop="userName" :show-overflow-tooltip="true"/>
          <el-table-column label="用户昵称" align="center" prop="nickName" :show-overflow-tooltip="true"/>
          <el-table-column label="部门" align="center" prop="dept.deptName" :show-overflow-tooltip="true"/>
          <el-table-column label="手机号码" align="center" prop="phonenumber" width="120"/>
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="180"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
              >修改
              </el-button>
              <el-button
                v-if="scope.row.userId !== 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
              >删除
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-key"
                @click="handleResetPwd(scope.row)"
                v-hasPermi="['system:user:resetPwd']"
              >重置
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="pageNum"
          :limit.sync="pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <add-or-update v-show="open" @on-close="open=false" ref="addOrUpdate"></add-or-update>

    <!-- 用户导入对话框 -->
    <Upload v-show="uploadOpen" @on-close="uploadOpen=false" ref="upload"></Upload>
  </div>
</template>

<script>
  import {
    listUser,
    getUser,
    delUser,
    exportUser,
    resetUserPwd,
    changeUserStatus
  } from '@/api/system/user'
  import {treeselect} from '@/api/system/dept'
  import AddOrUpdate from './add-or-update'
  import Upload from './upload'

  import mixinViewModule from '@/mixins/view-module'

  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    name: 'User',
    mixins: [mixinViewModule],
    components: {AddOrUpdate, Upload, Treeselect},
    data() {
      return {
        mixinViewModuleOptions: {
          getDetailsURL: getUser,// 查询详情实体
          getDataListURL: listUser, // 数据列表接口，API地址
          deleteURL: delUser, // 删除接口，API地址
          tableKey: 'userId', // 删除接口，批量状态下由那个key进行标记操作？比如：pid，uid...
          exportURL: exportUser // 导出接口，API地址
        },
        showDept: true,
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 弹出层标题
        title: '',
        // 部门树选项
        deptOptions: undefined,
        // 是否显示弹出层
        open: false,
        uploadOpen: false,
        // 部门名称
        deptName: undefined,
        // 日期范围
        dateRange: [],
        // 状态数据字典
        statusOptions: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        // 查询参数
        queryParams: {
          userName: undefined,
          phonenumber: undefined,
          status: undefined,
          deptId: undefined
        }
      }
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val)
      }
    },
    created() {
      this.getTreeselect()
      this.getDicts('sys_normal_disable').then(response => {
        this.statusOptions = response.data
        this.$refs.addOrUpdate.statusOptions = response.data
      })
      this.getDicts('sys_user_sex').then(response => {
        this.sexOptions = response.data
        this.$refs.addOrUpdate.sexOptions = response.data
      })
      this.getList();
    },
    methods: {
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data
          this.$refs.addOrUpdate.deptOptions = response.data
        })
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deptId = data.id
        this.getList()
      },
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status === '0' ? '启用' : '停用'
        this.$confirm('确认要"' + text + '""' + row.userName + '"用户吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return changeUserStatus(row.userId, row.status)
        }).then(() => {
          this.msgSuccess(text + '成功')
        }).catch(function () {
          row.status = row.status === '0' ? '1' : '0'
        })
      },
      onResetQuery() {
        this.dateRange = []
      },
      onStartQuery() {
        this.addDateRange(this.queryParams, this.dateRange)
      },
      onOpenHandleDialog() {
        this.getTreeselect()
        getUser().then(response => {
          this.postOptions = response.posts
          this.roleOptions = response.roles
          this.$refs.addOrUpdate.postOptions = response.posts
          this.$refs.addOrUpdate.roleOptions = response.roles
        });
      },
      onHandleDetails(data, type) {
        this.postOptions = data.posts
        this.roleOptions = data.roles
        this.$refs.addOrUpdate.postOptions = data.posts
        this.$refs.addOrUpdate.roleOptions = data.roles
        if (type == this.$formType.edit) {
          this.$refs.addOrUpdate.form = data.data
          this.$refs.addOrUpdate.form.postIds = data.postIds
          this.$refs.addOrUpdate.form.roleIds = data.roleIds
        }
      },
      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        this.$prompt('请输入"' + row.userName + '"的新密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({value}) => {
          resetUserPwd(row.userId, value).then(response => {
            if (response.code === 200) {
              this.msgSuccess('修改成功，新密码是：' + value)
            } else {
              this.msgError(response.msg)
            }
          })
        }).catch(() => {
        })
      }
      ,
      /** 导入按钮操作 */
      handleImport() {
        this.$refs.upload.title = '用户导入'
        this.$refs.upload.open = true;
        this.uploadOpen = true
      },
      onShowDept() {
        this.showDept = !this.showDept
      }
    }
  }
</script>
